package cn.com.java.aspect;

import cn.com.java.annotation.SystemLog;
import cn.com.java.model.SysLog;
import cn.com.java.service.SysLogService;
import com.alibaba.fastjson2.JSON;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.Json;

import java.lang.reflect.Method;

/**
 * @author liushuntao
 * @date 2024/1/11
 */
@Component
@Slf4j
@Aspect
@EnableAspectJAutoProxy
@AllArgsConstructor
public class SysLogAspect {

    private final SysLogService sysLogService;

    @Pointcut("@annotation(cn.com.java.annotation.SystemLog)")
    public void logProct() {

    }

    @Around("logProct()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long begin = System.currentTimeMillis();
        Object proceed = proceedingJoinPoint.proceed();
        long time = System.currentTimeMillis() - begin;
        saveSyslog(time, proceedingJoinPoint);
        return proceed;
    }

    /**
     * @param time
     * @param proceedingJoinPoint
     */
    private void saveSyslog(long time, ProceedingJoinPoint proceedingJoinPoint) {
        SysLog sysLog = new SysLog();
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method method = signature.getMethod();
        SystemLog systemLog = method.getAnnotation(SystemLog.class);
        if (systemLog != null) {
            //设置方法绑定名称
            sysLog.setOperation(systemLog.value());
        }
        String className = proceedingJoinPoint.getTarget().getClass().getName();
        //设置方法名称
        sysLog.setMethod(className + "." + signature.getName() + "()");

        //获取方法参数
        Object[] args = proceedingJoinPoint.getArgs();
        sysLog.setParams(JSON.toJSONString(args));
        //执行时间
        sysLog.setTime(time);

        sysLogService.save(sysLog);

    }

}
